<?php

namespace core;

class h5cphp
{
    public static $classMap = array();
    public $assignArr = array();
    /**
     * 启动
     * @throws \Exception
     */
    static public function run()
    {
        //        p('ok');
        //启动日志类
        \core\lib\H5Log::init();
        \core\lib\H5Log::log('test');
        \core\lib\H5Log::log('test');
        \core\lib\H5Log::log('test');
        //初始化路由
        $route = new \core\lib\route();
        $ctrlClass = $route->ctrl;
        $action = $route->action;
        //判断控制器是否存在
        $ctrlFile = H5APP . '/Controllers/' . $ctrlClass . 'Controller.php';
        if (is_file($ctrlFile)) {
            include $ctrlFile;
            $ctrlClass = H5MODULE . '\\Controllers\\' . $ctrlClass . 'Controller';
            $ctrl = new $ctrlClass();
            $ctrl->$action(); //调用控制器方法
            //记录日志
            \core\lib\H5Log::log('访问：' . $ctrlClass . '@' . $action);
        } else {
            throw  new \Exception('找不到控制器：' . $ctrlClass);
        }
        //        $ctrlClass = '\\'.MODULE.'\Controllers\\'.$ctrlClass.'Controller';
        //       p($route);
    }

    /**
     * @param 需要加载的类
     * @return bool
     */
    static public function load($class)
    {
        //自动加载类库
        //类名的namespace是反斜线，要替换成正斜线；
        //        如果已经加载，就不用再次加载了， require_once就行了
        if (!isset($classMap[$class])) {
            $class = str_replace('\\', '/', $class);
            $file = str_replace('\\', '/', H5ROOT) . '/' . $class . '.php';
            if (is_file($file)) {
                include $file;
                self::$classMap[$class] = $class;
            } else {
                return false;
            }
        }
        return true;
    }

    public function assign($name, $value)
    {
        $this->assignArr[$name] = $value;
    }

    public function view($file)
    {
        //        使用twig模板引擎
        $path = H5APP . '/views/' . $file . '.html';
        //        dd($file);
        if (is_file($path)) {
            //把数组的键值对作为变量   提取出来  array('h'=>1)  --> $h = 1, 然后可以直接用$h
            extract($this->assignArr);
            $loader = new \Twig\Loader\FilesystemLoader(H5APP . '/views');
            $twig = new \Twig\Environment($loader, [
                'cache' => H5APP . '/log/twig',
                'debug' => DEBUG
            ]);
            $template = $twig->load($file . '.html');
            $template->display($this->assignArr ? $this->assignArr : array());
        }
        //        $file = H5APP.'/'.$file;
        ////        p($file);
        //        if (is_file($file)){
        //            //把数组的键值对作为变量   提取出来  array('h'=>1)  --> $h = 1, 然后可以直接用$h
        //            extract($this->assignArr);
        ////            p($this->assign);
        //            include $file;
        //        }
    }
}